/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2024 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "gpio.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "adc_proc.h"
#include "cc1101.h"
#include "com.h"
#include <string.h>

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define SERIAL_FRAME_HEADER 0x43
#define TASK_INTERVAL 1000
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
rf_source_t rf_source = {NULL};
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void Flash_Init(rf_flash_t *flash);
void Serial_Receive_Callback();
void RS485_Receive_Callback();
void RF_SourceInit(rf_source_t *source);
void Attenuator_SetInt(uint16_t val);
void Attenuator_SetFloat(float val);
void RF_Output_Enable();
void RF_Output_Disable();
void RF_SetOutputLevel(uint8_t level);
void VCtrl_Run();
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void Task_Run()
{
    if (HAL_GetTick() % TASK_INTERVAL == 0)
    {
        LED_TWINKLE();
        rf_source.current = adc_proc.fields.current * (3.3f / 4095.0f) / 0.6f;
        rf_source.temperature = adc_proc.fields.temperature * (3.3f / 4095.0f);
        rf_source.detection = adc_proc.fields.rf_wave * (3.3f / 4095.0f);
    }
}
/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{

    /* USER CODE BEGIN 1 */

    /* USER CODE END 1 */

    /* MCU Configuration--------------------------------------------------------*/

    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();

    /* USER CODE BEGIN Init */

    /* USER CODE END Init */

    /* Configure the system clock */
    SystemClock_Config();

    /* USER CODE BEGIN SysInit */

    /* USER CODE END SysInit */

    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_DMA_Init();
    MX_DAC_Init();
    MX_USART1_UART_Init();
    MX_USART3_UART_Init();
    MX_ADC1_Init();
    MX_SPI1_Init();
    MX_TIM16_Init();
    /* USER CODE BEGIN 2 */
    Serial_Init(&huart1, Serial_Receive_Callback);
    RS485_Init(&huart3, RS485_Receive_Callback);

    ADC_PROC_Start();
    HAL_TIM_Base_Start_IT(&htim16);

    RF_SourceInit(&rf_source);
    /* USER CODE END 2 */

    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    Serial_Print("System initialization complete\n");
    while (1)
    {
        Task_Run();
        VCtrl_Run();
        /* USER CODE END WHILE */

        /* USER CODE BEGIN 3 */
        Serial_Run();
        RS485_Run();
    }
    /* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

    /** Initializes the RCC Oscillators according to the specified parameters
     * in the RCC_OscInitTypeDef structure.
     */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
    RCC_OscInitStruct.HSEState = RCC_HSE_ON;
    RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }

    /** Initializes the CPU, AHB and APB buses clocks
     */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
    {
        Error_Handler();
    }
    PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_ADC12;
    PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
    PeriphClkInit.Usart3ClockSelection = RCC_USART3CLKSOURCE_PCLK1;
    PeriphClkInit.Adc12ClockSelection = RCC_ADC12PLLCLK_DIV1;
    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
    {
        Error_Handler();
    }
}

/* USER CODE BEGIN 4 */

void RF_SourceInit(rf_source_t *source)
{
    source->setup.output = kOFF;
    source->setup.v_ctrl = kOFF;
    source->attenuation = ATTENUATOR_MAX_VAL;

    Flash_Init(&source->flash);
    Attenuator_SetFloat(source->attenuation);
    HAL_DAC_Start(&hdac, DAC_CHANNEL_1);
    CC1101_Init();
    RF_SetOutputLevel(source->flash.config.output_level);
}

void Flash_Init(rf_flash_t *flash)
{
    const static rf_flash_t kFlashDefault = {
        .init = 1,
        .config.output_level = 7,
    };
    rf_flash_t flash_read;
    Flash_Read(FLASH_START_ADDR, (uint32_t *)&flash_read, sizeof(rf_flash_t) / sizeof(uint32_t));
    if (flash_read.init != FLASH_DEFAULT_INITIAL_VALUE)
    {
        if (Flash_Write(FLASH_START_ADDR, (uint32_t *)&kFlashDefault, sizeof(rf_flash_t) / sizeof(uint32_t)))
            Serial_Print("Flash memory initialization failed!\n");
        else
            Serial_Print("Flash memory initialization complete\n");
    }
    else
    {
        memcpy(flash, &flash_read, sizeof(rf_flash_t));
        Serial_Print("Flash memory data loaded\n");
    }
}

void Attenuator_SetInt(uint16_t val)
{
    if (val > 4095)
        val = 4095;
    rf_source.attenuation = val * (ATTENUATOR_MAX_VAL / 4095.0f);
    HAL_DAC_SetValue(&hdac, DAC_CHANNEL_1, DAC_ALIGN_12B_R, 4095 - val);
}

void Attenuator_SetFloat(float val)
{
    if (val < 0 || val > ATTENUATOR_MAX_VAL)
        return;
    Attenuator_SetInt((uint16_t)(val * (4095 / ATTENUATOR_MAX_VAL)));
}

void VCtrl_Run()
{
    if (rf_source.setup.v_ctrl != kON)
        return;
    rf_source.input_voltage = adc_proc.fields.voltage * (3.3f / 4095.0f);
    if (rf_source.setup.output == kOFF && rf_source.input_voltage > 0.5f)
        RF_Output_Enable();
    else if (rf_source.setup.output == kON && rf_source.input_voltage < 0.5f)
        RF_Output_Disable();
    Attenuator_SetInt(adc_proc.fields.voltage);
}

void RF_Output_Enable()
{
    POWER_28V_ENABLE();
    delay_ms(100);
    CC1101_Output_Enable();
    rf_source.setup.output = kON;
}

void RF_Output_Disable()
{
    CC1101_Output_Disable();
    Attenuator_SetFloat(ATTENUATOR_MAX_VAL);
    delay_ms(100);
    POWER_28V_DISABLE();
    rf_source.setup.output = kOFF;
}

void RF_SetOutputLevel(uint8_t level)
{
    if (level > 7)
        level = 7;
    rf_source.flash.config.output_level = level;
    CC1101_SetOutputLevel(level);
}

void Serial_Receive_Callback()
{
    static data_type_change_t data;
    if (serial.payload[0] == SERIAL_FRAME_HEADER)
    {
        for (uint8_t i = 0; i < sizeof(data_type_change_t); i++)
        {
            data.byte[i] = serial.payload[1 + sizeof(data_type_change_t) - i];
        }
        switch (serial.payload[1])
        {
        case 0: // RF Source Info
            Serial_Print("433MHz RF Source\n"
                         "Compilation date: %s\n"
                         "Output: %s\n"
                         "Level: %d\n"
                         "Control mode: %s\n"
                         "InputVoltage: %5.2fV\n"
                         "Attenuation:  %5.2fdB\n"
                         "Temperature:  %5.2fC\n"
                         "Detection:    %5.2f\n"
                         "Current:      %5.2fA\n",
                         __DATE__, rf_source.setup.output ? "Enabled" : "Disabled", rf_source.flash.config.output_level,
                         rf_source.setup.v_ctrl ? "Voltage" : "Serial", rf_source.input_voltage, rf_source.attenuation,
                         rf_source.temperature, rf_source.detection, rf_source.current);
            break;
        case 1: // RF Output Enable/Disable;
            if (data.word)
            {
                RF_Output_Enable();
            }
            else
            {
                RF_Output_Disable();
            }
            Serial_Print("RF Output %s\n", rf_source.setup.output ? "Enabled" : "Disabled");
            break;
        case 2: // RF Output Level
            RF_SetOutputLevel(data.word);
            Flash_Write(FLASH_START_ADDR, (uint32_t *)&rf_source.flash, sizeof(rf_flash_t) / sizeof(uint32_t));
            Serial_Print("RF Output Level: %d\n", rf_source.flash.config.output_level);
            break;
        case 3: // Attenuator Set
            if (rf_source.setup.v_ctrl == kOFF)
            {
                Attenuator_SetFloat(data.decimal);
                Serial_Print("Attenuator Set: %5.2fdB\n", rf_source.attenuation);
            }
            else
            {
                Serial_Print("Control mode must be Serial to set attenuation\n");
            }
            break;
        case 4: // Control mode
            rf_source.setup.v_ctrl = data.word;
            Serial_Print("Control mode: %s\n", rf_source.setup.v_ctrl ? "Voltage" : "Serial");
            break;
        }
    }
}

void RS485_Receive_Callback()
{
    /* 处理代码 */
}
/* USER CODE END 4 */

/**
 * @brief  Period elapsed callback in non blocking mode
 * @note   This function is called  when TIM17 interrupt took place, inside
 * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
 * a global variable "uwTick" used as application time base.
 * @param  htim : TIM handle
 * @retval None
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    /* USER CODE BEGIN Callback 0 */

    /* USER CODE END Callback 0 */
    if (htim->Instance == TIM17)
    {
        HAL_IncTick();
    }
    /* USER CODE BEGIN Callback 1 */
    if (htim->Instance == TIM16)
    {
        ADC_RecursiveMeanFilter();
    }
    /* USER CODE END Callback 1 */
}

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1)
    {
    }
    /* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT
/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
    /* USER CODE BEGIN 6 */
    /* User can add his own implementation to report the file name and line number,
       ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
